#!/bin/bash

set -e

funCheckParam() {
	if [ 1 = $# ]; then
		return
	fi
	return 1
}

if ! funCheckParam "$*" ; then
	echo "Invalid parameter."
	exit 1
fi

WORK_HOME=./uploads/cert
APPKEY=$1


WORK_DIR=$WORK_HOME/$APPKEY

if [ -d "$WORK_DIR" ]; then
#	echo "APPKEY already exists."
#	exit 2
  rm -rf $WORK_DIR
fi

mkdir -p "$WORK_DIR"/{private,certs,server,client}

openssl genrsa -out "$WORK_DIR"/private/ca.key 4096
openssl req -new -x509 -days 3650 -key "$WORK_DIR"/private/ca.key -out "$WORK_DIR"/certs/ca.crt -subj /C=CN/ST=HK/L=HK/O=C"$APPKEY"/OU=/CN=/emailAddress=/

openssl genrsa -out "$WORK_DIR"/private/server.key 2048
openssl req -new -key "$WORK_DIR"/private/server.key -out "$WORK_DIR"/certs/server.csr -subj /C=CN/ST=HK/L=HK/O=C"$APPKEY"/OU=/CN=Server/emailAddress=/
openssl x509 -req -days 365 -in "$WORK_DIR"/certs/server.csr -CA "$WORK_DIR"/certs/ca.crt -CAkey "$WORK_DIR"/private/ca.key -set_serial 01 -out "$WORK_DIR"/certs/server.crt

openssl genrsa -out "$WORK_DIR"/private/client.key 2048
openssl req -new -key "$WORK_DIR"/private/client.key -out "$WORK_DIR"/certs/client.csr -subj /C=CN/ST=HK/L=HK/O=C"$APPKEY"/OU=/CN=Client/emailAddress=/
openssl x509 -req -days 365 -in "$WORK_DIR"/certs/client.csr -CA "$WORK_DIR"/certs/ca.crt -CAkey "$WORK_DIR"/private/ca.key -set_serial 02 -out "$WORK_DIR"/certs/client.crt

openssl pkcs12 -export -in "$WORK_DIR"/certs/client.crt -out "$WORK_DIR"/certs/client.p12 -inkey "$WORK_DIR"/private/client.key -passout pass:"$APPKEY"


cp "$WORK_DIR"/certs/{server,ca}.crt "$WORK_DIR"/private/server.key "$WORK_DIR"/server

cp "$WORK_DIR"/certs/client.crt "$WORK_DIR"/client/client.cer
cp "$WORK_DIR"/certs/client.p12 "$WORK_DIR"/client
